package edu.manju.mimi.core.security;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * <h4>mimi-core</h4>
 * <p>应用@NeedAuth于参数, 获取登录的用户ID</p>
 *
 * @author : Lebei(lebei163@163.com)
 * @date : 2023-03-03 20:38
 **/
public class LoginUserIdResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Integer.class)
                && parameter.hasParameterAnnotation(CurrentUserId.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Integer userId = (Integer) webRequest.getAttribute(LoginInterceptor.CURRENT_USER, RequestAttributes.SCOPE_REQUEST);
        return userId;
    }
}
